<?php
defined ( 'BASEPATH' ) or exit ( 'No direct script access allowed' );
class Lost_model extends CI_Model {
	public function __construct() {
		parent::__construct ();
	}
	/*
	 * 根据分页信息返回库存损耗列表
	 */
	public function find_all_losts($name,$per_page,$offset){
		$this->db->select('t_lost.id,t_product.name,t_lost.amount,t_lost.total,t_lost.note,t_lost.type,t_lost.lost_time');
		$this->db->from('t_lost');
		$this->db->join('t_product', 't_lost.productid = t_product.id','left');
		if(!empty($name)){
			$this->db->like('name', $name);
		}
		$this->db->limit($per_page, $offset);
		$this->db->order_by("id", "desc");
		$query = $this->db->get();
		return $query->result_array();
	}
	/*
	 * 返回库存损耗数量
	 */
	public function count_losts($name){
		$this->db->join('t_product', 't_lost.productid = t_product.id','left');
		if(!empty($name)){
			$this->db->like('name', $name);
		}
		$query = $this->db->get('t_lost');
		return $query->num_rows();
	}
	/*
	 * 根据ID返回损耗
	 */
	public function load($id){
		$query = $this->db->get_where('t_lost',array('id' => $id));
		if ($row = $query->row_array()){
			return $row;
		}
		return array();
	}
	/*
	 * 添加库存损耗信息
	 */
	public function create($lost){
		$this->db->insert('t_lost', $lost);
		return $this->db->insert_id();
	}
	/*
	 * 删除库存损耗信息
	 */
	public function delete($id){
		$this->db->where('id', $id);
		$this->db->delete('t_lost');
		return $this->db->affected_rows()>0;
	}
	/*
	 * 根据起始日期得到损耗的商品信息
	 */
	public function get_products_by_date($startdate,$enddate){//
			$sql="select productid,sum(amount) as amount from t_lost 
					where t_lost.lost_time>='".$startdate."' and  t_lost.lost_time<='".$enddate."' group by productid";
		$query = $this->db->query($sql);
		return $query->result_array();
	}
	/*
	 * 根据起始日期和商品ID得到损耗的商品信息(用于添加库存商品)
	 */
	public function get_lost_by_date_product($productid,$startdate,$enddate){//
			$sql="select productid,sum(amount) as amount from t_lost 
					where productid=".$productid." and t_lost.lost_time>='".$startdate."' and  t_lost.lost_time<='".$enddate."'";
		$query = $this->db->query($sql);
		return $query->row_array();
	}
	/*
	 * 根据商品ID得到线下周销售量
	 */
	public function get_weeklyamount_by_product($productid){
		$this->db->select('sum(amount) as amount');
		$this->db->from('t_lost');
		$this->db->where('productid',$productid);
		$this->db->where('type=1');
		$this->db->where("TO_DAYS(NOW())-TO_DAYS(lost_time)<=7");
		$query = $this->db->get();
		return $query->row_array();
	}
	/*
	 * 根据商品ID得到线下月销售量
	 */
	public function get_monthlyamount_by_product($productid){
		$this->db->select('sum(amount) as amount');
		$this->db->from('t_lost');
		$this->db->where('productid',$productid);
		$this->db->where('type=1');
		$this->db->where("TO_DAYS(NOW())-TO_DAYS(lost_time)<=30");
		$query = $this->db->get();
		return $query->row_array();
	}
}